﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hotel.Domain;
using Hotel.Util;
using System.Data.Common;
namespace HOTEL.Dao
{
    public class GroupPerDao:BaseDAO
    {
        public GroupPermission Gets(int GroupId, int PageId,int Permission)
        {
            return _db.GroupPermissions.Where(p => p.GroupId.Equals(GroupId)
                && p.PageId.Equals(PageId)
                && p.Active.HasValue && p.Active.Value
                && p.Permission.Equals(Permission)).SingleOrDefault();
        }
        public bool HasPermission(int Permission,int PageId, int manv)
        {
            //
            var groups = _db.GroupUsers.Where(p => p.UserId.Equals(manv)).ToList();
            if (groups == null || groups.Count == 0)
                return false;
            foreach (var item in groups)
            {
                var grP = _db.GroupPermissions.Where(p => p.Permission.Equals(Permission)
                    && p.PageId.Equals(PageId)
                    && p.GroupId.Equals(item.GroupId)
                    && p.Active.HasValue && p.Active.Value).SingleOrDefault();
                if (grP != null)
                    return true;
            }
            return false;
        }

        public bool HasPer(int GroupId, int PageId, int Permission)
        {
            return _db.GroupPermissions.Where(p => p.GroupId.Equals(GroupId) && p.PageId.Equals(PageId) && p.Permission.Equals(Permission)).Count() > 0;
        }
        
        public Message UpdateList(List<GroupPermission> objList,Group grcurrent)
        {
            Message msg;
            DbTransaction trans = null;

            try
            {
                _db.Connection.Open();
                trans = _db.Connection.BeginTransaction();
                _db.Transaction = trans;
                var list = _db.GroupPermissions.Where(p => p.GroupId.Equals(grcurrent.Id)).ToList();
                _db.GroupPermissions.DeleteAllOnSubmit(list);
                _db.SubmitChanges();
                _db.GroupPermissions.InsertAllOnSubmit(objList);
                _db.SubmitChanges();
                // commit
                trans.Commit();
                // success message
                msg = new Message(MessageConstants.I_DELETE_SUCCEED, MessageType.Info, objList.Count + " phân quyền ");
            }
            catch (Exception ex)
            {
                // rollback transaction
                if (trans != null)
                    trans.Rollback();

                msg = ExceptionHandler.HandleInsertException(ex, " phân quyền ");
            }

            return msg;
        }
       
    }
}
